package com.ele.client;

import com.ele.client.activity.auth.LoginPlace;
import com.ele.client.rpc.SimpleAsyncCallback;
import com.ele.client.util.UserHelper;
import com.ele.model.AppUser;
import com.google.gwt.activity.shared.ActivityManager;
import com.google.gwt.activity.shared.ActivityMapper;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.place.shared.Place;
import com.google.gwt.place.shared.PlaceController;
import com.google.gwt.place.shared.PlaceHistoryHandler;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.SimplePanel;
import com.google.web.bindery.event.shared.EventBus;

public class Application implements EntryPoint {

    private Place defaultPlace = new LoginPlace(null);
    private SimplePanel appWidget = new SimplePanel();

    public void onModuleLoad() {
        ClientFactory clientFactory = GWT.create(ClientFactory.class);
        EventBus eventBus = clientFactory.getEventBus();
        PlaceController placeController = clientFactory.getPlaceController();

        // Start ActivityManager for the main widget with our ActivityMapper
        ActivityMapper activityMapper = new AppActivityMapper(clientFactory);
        ActivityManager activityManager = new ActivityManager(activityMapper, eventBus);
        activityManager.setDisplay(appWidget);

        // Start PlaceHistoryHandler with our PlaceHistoryMapper
        AppPlaceHistoryMapper historyMapper = GWT.create(AppPlaceHistoryMapper.class);
        final PlaceHistoryHandler historyHandler = new PlaceHistoryHandler(historyMapper);
        historyHandler.register(placeController, eventBus, defaultPlace);

        RootPanel.get().add(appWidget);

        clientFactory.getApplicationService().getUser(new SimpleAsyncCallback<AppUser>() {
            @Override
            public void onSuccess(AppUser result) {
                UserHelper.setUser(result);
                // Goes to the place represented on URL else default place
                historyHandler.handleCurrentHistory();
            }
        });


//        ApplicationServiceAsync rpcService = GWT.create(ApplicationService.class);
//        HandlerManager eventBus = new HandlerManager(null);
//        AppController appViewer = new AppController(rpcService, eventBus);
//        appViewer.go(RootPanel.get());
    }
}
